import json
import urllib
from haralyzer import HarParser
# from record import Reqparser
# 从HAR文件中加载数据
def handle_form(data):
    """
    处理 Content-Type:	application/x-www-form-urlencoded
    默认生成的数据 username=admin&password=123456
    :param data: 获取的data 类似这样  username=admin&password=123456
    :return:
    """
    data_dict = {}

    if isinstance(data,dict) or isinstance(data,list):  # 如果是字典或列表，直接返回
        return data
    elif isinstance(data, str):
        try:
            for i in data.split("&"):
                data_dict[i.split("=")[0]] = i.split("=")[1]
            return data_dict  # 拼成字典
        except IndexError:
            return ""
def har_case(harfile):

    with open("case/"+harfile+".har","r",encoding="utf-8") as har_file:
        har_data = json.loads(har_file.read())

    har_parser = HarParser(har_data)
    parsed_data = har_parser.har_data
    har_list =parsed_data["entries"]

    ignore_list = [
        '/cm/api/v1/menu/myMenu',
        '/cm/api/v1/user/info/get/basic-info',
        '/cm/file/upload',
        '/cm/api/homepage/workbench/monitorVehicleGisList',
        '/cm/file/download',
        '/cm/api/menu/current_user_menu'
        # 'pageNumber=1&pageSize=10&projectName='
        # '/ipc/api/v1/approval-manage/todo-list'

    ]  # 忽略路由守卫的url
    request_list=[]
    for har in har_list:
        request_info = {}
        conditions = [
            not har["request"]["url"].startswith('http://shuiniche.ningdatech.com/cm/'),
            urllib.parse.urlparse(har["request"]["url"])[2] in ignore_list,
            # flow.request.url.endswith('pageNumber=1&pageSize=10&projectName='),
            # flow.request.url[-1].isdigit()
        ]


        if any(conditions):

            pass

        else:
            # print(har["request"]["url"])
        #
            url = har["request"]["url"]
            print(url)
            path = urllib.parse.urlparse(har["request"]["url"])[2]
            if url.startswith('http://shuiniche.ningdatech.com/cm/api/v1/user/auth/login/password'):
                if len(har["request"]["cookies"])>0:
                    ND_JSESSION = har["response"]["cookies"][0]["value"]
                    print(har["request"])
                    XSRF_TOKEN = har["request"]["cookies"][0]["value"]
                    headers = "XSRF-TOKEN={}; ND_JSESSION={}".format(XSRF_TOKEN,ND_JSESSION)
                else:
                    ND_JSESSION = har["response"]["cookies"][1]["value"]

                    XSRF_TOKEN = har["response"]["cookies"][0]["value"]
                    headers = "XSRF-TOKEN={}; ND_JSESSION={}".format(XSRF_TOKEN,ND_JSESSION)
            # # headers = flow.request.headers["Cookie"]
            else:
                for header in  har["request"]["headers"]:
                    if header["name"]=="Cookie":
                        headers = ";".join(header["value"].split(";")[0:2])

            method =har["request"]["method"].lower()

            if "?" in url:
                url,payload = url.split("?")
                data= {}
            elif url.split('/')[-1].isdigit() :
                payload = {"PathParameter": url.split('/')[-1]}
                data = {}
            elif  har["request"]["queryString"] == [] and not har["request"].get("postData"):
                payload = {}
                data = {}
            if har["request"].get("postData"):
                if har["request"].get("postData").get("mimeType") =="application/json":

                    payload = json.loads(har["request"].get("postData")["text"])
                    data = {}
                elif har["request"].get("postData").get("mimeType").startswith("multipart/form-data"):
                    data = har["request"].get("postData")
                    text = data["text"]

                    # 解析文本，提取字段名称和值
                    fields = {}
                    lines = text.split("\r\n")
                    for line in lines:
                        if line.startswith("Content-Disposition"):
                            name = line.split('name="')[1].split('"')[0]
                        elif line and not line.startswith("-"):
                            fields[name] = line

                    data = {param["name"]: param["value"] for param in data["params"]}
                    payload = {}
            else:
                payload ={item["name"]: item["value"] for item in har["request"]["queryString"]}
                data = {}
            payload = handle_form(payload)
            if url.split('/')[-1].isdigit() :
                payload ["PathParameter"]= url.split('/')[-1]
            print(url)
            res =json.loads(har["response"]["content"]["text"])
            request_info["url"] = url
            request_info["method"] = method
            request_info["headers"] = headers
            request_info["data"] =data
            request_info['payload'] = payload

            request_info["res"] = res
            request_info["title"] = harfile
            request_list.append(request_info)

    list1 = []

    #
    Reqparser.flow_save_cases(request_list,"水泥车", 'request_list.yaml')
    path_list = Reqparser.get_result(request_list)
    #

    # Reqparser.flow_save_cases(path_list, "水泥车",'path_list.yaml')
    same_list = Reqparser.find_same_key(path_list, "originint")
    reverse_dfs_list = Reqparser.reverse_dfs(same_list, list1)

    Reqparser.flow_save_cases(reverse_dfs_list, "水泥车",'test.yaml')

def post_data( post_data: dict):
    """
    处理请求数据类型
    :param post_data:
    :return:
    """
    if post_data['mimeType'] is None:
        return ['other', {}]

    if 'application/x-www-form-urlencoded' in post_data['mimeType']:
        return ['body', {params['name']: params['value'] for params in post_data['params']}]

    if 'application/json' in post_data['mimeType']:
        return ['json', json.loads(post_data['text'])]

    if 'multipart/form-data' in post_data['mimeType']:
        return ['file', post_data['params']]

    return ['other', {}]
#解析har文件
def har_reuqest(harfile):
    FILTER_MIME_TYPE = [
        'application/javascript',
        'text/css',
        'image/png',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/bmp',
        'image/webp',
        'image/x-icon',
        'image/vnd',
        'microsoft.icon',
    ]
    har_parser = HarParser(harfile)


    parsed_data = har_parser.har_data
    har_list =parsed_data["entries"]
    # print(har_list)
    # ignore_list = [
    #     '/cm/api/v1/menu/myMenu',
    #     '/cm/api/v1/user/info/get/basic-info',
    #     '/cm/file/upload',
    #     '/cm/api/homepage/workbench/monitorVehicleGisList',
    #     '/cm/file/download',
    #     '/cm/api/menu/current_user_menu'
    #     # 'pageNumber=1&pageSize=10&projectName='
    #     # '/ipc/api/v1/approval-manage/todo-list'
    #
    # ]  # 忽略路由守卫的url
    request_list=[]
    index = 0
    for har in har_list:
        if har['response']['content'].get('mimeType') in FILTER_MIME_TYPE:
            continue
        index+=1
        request_info = {}
        # conditions = [
        #     not har["request"]["url"].startswith('http://shuiniche.ningdatech.com/cm/'),
        #     urllib.parse.urlparse(har["request"]["url"])[2] in ignore_list,
        #     # flow.request.url.endswith('pageNumber=1&pageSize=10&projectName='),
        #     # flow.request.url[-1].isdigit()
        # ]
        #
        #
        # if any(conditions):
        #
        #     pass
        #
        # else:
            # print(har["request"]["url"])
        #
        url = har["request"]["url"]

        path = urllib.parse.urlparse(har["request"]["url"])[2]
        # if url.startswith('http://shuiniche.ningdatech.com/cm/api/v1/user/auth/login/password'):
        #     if len(har["request"]["cookies"])>0:
        #         ND_JSESSION = har["response"]["cookies"][0]["value"]
        #         print(har["request"])
        #         XSRF_TOKEN = har["request"]["cookies"][0]["value"]
        #         headers = "XSRF-TOKEN={}; ND_JSESSION={}".format(XSRF_TOKEN,ND_JSESSION)
        #     else:
        #         ND_JSESSION = har["response"]["cookies"][1]["value"]
        #
        #         XSRF_TOKEN = har["response"]["cookies"][0]["value"]
        #         headers = "XSRF-TOKEN={}; ND_JSESSION={}".format(XSRF_TOKEN,ND_JSESSION)
        # # # headers = flow.request.headers["Cookie"]
        # else:
        #     for header in  har["request"]["headers"]:
        #         if header["name"]=="Cookie":
        #             headers = ";".join(header["value"].split(";")[0:2])

        for header in  har["request"]["headers"]:
            if header["name"]=="Cookie":
                headers = ";".join(header["value"].split(";")[0:2])
        method =har["request"]["method"].lower()
        if har['request'].get('queryString'):
            query = {query['name']: query['value'] for query in har['request']['queryString']}
        else:
            query = {}

            # 处理请求中 body和json数据
            if har['request'].get('postData'):
                body_json =  post_data(har['request']['postData'])
            else:
                body_json = ['body', {}]

            if 'application/json' in str(har['response']['content'].get('mimeType')):
                if har['response']['content'].get('text'):
                    # res_data = json.loads(base64.b64decode(data['response']['content']['text'].encode('utf-8')))
                    res_data = json.loads(har['response']['content']['text'].encode('utf-8'))
                else:
                    res_data = {}
            elif 'text/json' in str(har['response']['content'].get('mimeType')):
                res_data = json.loads(har['response']['content']['text'])
            else:
                res_data = {}


        # if "?" in url:
        #     url,payload = url.split("?")
        #     data= {}
        # elif url.split('/')[-1].isdigit() :
        #     payload = {"PathParameter": url.split('/')[-1]}
        #     data = {}
        # elif  har["request"]["queryString"] == [] and not har["request"].get("postData"):
        #     payload = {}
        #     data = {}
        # if har["request"].get("postData"):
        #     if har["request"].get("postData").get("mimeType") =="application/json":
        #
        #         payload = json.loads(har["request"].get("postData")["text"])
        #         data = {}
        #     elif har["request"].get("postData").get("mimeType").startswith("multipart/form-data"):
        #         data = har["request"].get("postData")
        #         text = data["text"]
        #
        #         # 解析文本，提取字段名称和值
        #         fields = {}
        #         lines = text.split("\r\n")
        #         for line in lines:
        #             if line.startswith("Content-Disposition"):
        #                 name = line.split('name="')[1].split('"')[0]
        #             elif line and not line.startswith("-"):
        #                 fields[name] = line
        #
        #         data = {param["name"]: param["value"] for param in data["params"]}
        #         payload = {}
        # else:
        #     payload ={item["name"]: item["value"] for item in har["request"]["queryString"]}
        #     data = {}
        # payload = handle_form(payload)
        # if url.split('/')[-1].isdigit() :
        #     payload ["PathParameter"]= url.split('/')[-1]
        # print(url)
        # res =json.loads(har["response"]["content"]["text"])
        request_info["index"] = index
        request_info["url"] = url
        request_info["method"] = method
        request_info["headers"] = {header['name']: header['value'] for header in har['request']['headers']},
        request_info["query"] = query
        request_info['payload'] = 'json' if body_json[0] == 'json' else 'body',
        request_info["data"] =  body_json[1] if body_json[0] != 'file' else {},
        request_info["res"] = res_data
        # request_info["title"] = harfile
        request_list.append(request_info)
    return request_list

if __name__ == '__main__':
    har_case("驾驶员报名全流程")